<template>
  <view>
    <!-- 全局容器 -->
  </view>
</template>

<script>
// 内联视频默认数据（不变）
const DEFAULT_VIDEO_DATA = {
  "categories": ["推荐", "千里眼", "搞笑", "娱乐", "社会", "音乐", "科技"],
  "videoList": [
    {
      "id": 1,
      "title": "600斤的公牛不甘心被杀，宁愿跳进大海之中",
      "cover": "static/video1.mp4",
      "playCount": "1.2万",
      "duration": "01:15",
      "author": "醉里挑灯看剑",
      "isFollowed": false
    },
    {
      "id": 2,
      "title": "涉案金额80个亿的高仿名表",
      "cover": "static/video3.mp4",
      "playCount": "5.8万",
      "duration": "01:46",
      "author": "NORA",
      "isFollowed": false
    },
    {
      "id": 3,
      "title": "大兴安岭出现超大型野兽，体重一吨比轿车还大",
      "cover": "static/video2.mp4",
      "playCount": "5.3万",
      "duration": "04:08",
      "author": "动物大观察",
      "isFollowed": false
    }
  ],
  "videoDetails": {
    "1": {
      "title": "600斤的公牛不甘心被杀，宁愿跳进大海之中",
      "cover": "static/video1.mp4",
      "playCount": "1.2万",
      "duration": "01:15",
      "author": "醉里挑灯看剑",
      "publishTime": "12-12",
      "comments": [
        {
          "id": 201,
          "username": "网友872503",
          "time": "2小时前",
          "content": "大自然的魅力..."
        }
      ],
      "recommend": [
        {
          "id": 3,
          "title": "大兴安岭出现超大型野兽",
          "playCount": "5.3万"
        }
      ]
    }
  }
};

// 【完全替换为 news.json 内容】
const DEFAULT_NEWS_DATA = {
  "config": {
    "pageTitle": "新闻资讯",
    "weatherCity": "泉州",
    "defaultWeather": {
      "date": "12-15",
      "week": "星期一",
      "high": "18",
      "low": "8"
    }
  },
  "categories": ["推荐", "热点", "消费", "政策", "社会", "财经", "时政"],
  "newsList": [
    {
      "id": 1,
      "title": "14个月从100家开到1000家门店，蜜雪冰城为何买下这家精酿啤酒商",
      "author": "界面新闻",
      "comments": 56,
      "timedata": "2025.10.07",
      "isTop": true,
      "imageList": ["static/mixue.png"], // 适配uni-app路径，去掉前置/
      "tags": ["商业", "消费","社会"],
      "readCount": 12345
    },
    {
      "id": 2,
      "title": "赵一鸣用糖找零引争议：顾客晒半袋“找零糖”",
      "author": "常规报",
      "comments": 15545,
      "timedata": "2025.10.29",
      "isTop": false,
      "imageList": ["static/zym.jpg"],
      "tags": ["社会", "热点"],
      "readCount": 89762
    },
    {
      "id": 3,
      "title": "698亿“国补”落地 促消费再添新动力",
      "author": "央视新闻",
      "comments": 123,
      "timedata": "2025.10.02",
      "isTop": false,
      "imageList": ["static/guobu.png"],
      "tags": ["财经", "政策","消费"],
      "readCount": 5678
    },
    {
      "id": 4,
      "title": "学习二十届四中全会精神 推进高质量发展",
      "author": "人民日报",
      "comments": 555,
      "timedata": "2025.10.25",
      "isTop": true,
      "imageList": ["static/xuehui.jpg"],
      "tags": ["时政", "学习"],
      "readCount": 34567
    },
    {
      "id": 5,
      "title": "亚太合作新时代：共话区域经济发展新机遇",
      "author": "新华日报",
      "comments": 5027,
      "timedata": "2025.10.02",
      "isTop": false,
      "imageList": [],
      "tags": ["国际", "经济","时政"],
      "readCount": 28901
    },
    {
      "id": 6,
      "title": "桂林漓江生态保护再升级，游船实行“环保动力”改造",
      "author": "桂林日报",
      "comments": 342,
      "timedata": "2025.10.30",
      "isTop": false,
      "imageList": ["static/lijiang.png"],
      "tags": ["本地", "政策","热点"],
      "readCount": 9876
    }
  ],
  "adList": [
    {
      "id": 999,
      "title": "淘宝闪购，点外卖就上淘宝闪购",
      "author": "淘宝网",
      "images": ["static/new1.jpg", "static/new2.jpg", "static/new3.jpg"],
      "bgColor": "#fff8e6",
      "jumpUrl": "https://taobao.com "
    },
    {
      "id": 1000,
      "title": "新款手机发布会，限时优惠500元",
      "author": "Apple",
      "images": ["static/phone1.jpg", "static/phone2.jpg"],
      "bgColor": "#f0f8fb",
      "jumpUrl": "https://example.com/phone "
    }
  ],
  "newsDetails": {
    "1": {
      "title": "14个月从100家开到1000家门店，蜜雪冰城为何买下这家精酿啤酒商",
      "author": "界面新闻",
      "timedata": "2025.10.07 14:30",
      "readCount": 12345,
      "shareCount": 234,
      "likeCount": 0,
      "content": [
        "近日，蜜雪冰城旗下投资公司宣布收购某精酿啤酒品牌，引发行业关注。据悉，该精酿品牌成立仅14个月，已从100家门店扩张至1000家，覆盖全国20多个省份。",
        "蜜雪冰城相关负责人表示，收购后将保留该品牌独立运营，同时共享供应链资源，进一步降低成本。业内分析，蜜雪冰城此举意在布局中高端饮品市场，弥补现有产品矩阵的空白。",
        "数据显示，2024年中国精酿啤酒市场规模突破500亿元，年增长率达25%，成为饮品行业新的增长点。蜜雪冰城凭借其庞大的线下渠道和供应链优势，有望快速抢占市场份额。"
      ],
      "imageList": ["static/mixue.png"],
      "recommendNews": [
        {
          "id": 7,
          "title": "蜜雪冰城推出“9.9元精酿”，搅动低端市场",
          "author": "财经网",
          "timedata": "2025.10.08"
        },
        {
          "id": 8,
          "title": "2025饮品行业趋势：精酿啤酒成资本新宠",
          "author": "行业观察",
          "timedata": "2025.10.06"
        }
      ],
      "comments": [
        {
          "id": 101,
          "username": "网友小夏",
          "city": "广西桂林",
          "timedata": "2小时前",
          "content": "蜜雪冰城这步棋走得妙，下沉市场站稳后开始向上突破了！",
          "likeCount": 123,
          "replyCount": 15,
          "liked": false
        },
        {
          "id": 102,
          "username": "啤酒爱好者",
          "city": "广东深圳",
          "timedata": "3小时前",
          "content": "试过这家精酿，口感不错，希望收购后品质不变",
          "likeCount": 45,
          "replyCount": 3,
          "liked": false
        }
      ]
    },
    "2": {
      "title": "赵一鸣用糖找零引争议：顾客晒半袋“找零糖”",
      "author": "常规报",
      "timedata": "2025.10.29 09:15",
      "readCount": 89762,
      "shareCount": 1234,
      "likeCount": 0,
      "content": [
        "近日，有网友在社交平台爆料，在赵一鸣零食店消费后，商家用糖果代替硬币找零，引发广泛争议。该网友晒出的照片显示，找零的糖果装了半袋，价值约2元。",
        "对此，赵一鸣零食店官方回应称，因门店硬币储备不足，糖果找零是临时措施，顾客可选择是否接受，若不接受可前往收银台兑换现金。但部分网友表示，这种做法侵犯了消费者的选择权。",
        "律师表示，根据《消费者权益保护法》，商家不得强制消费者接受非现金找零，若消费者明确拒绝，商家应提供现金找零服务。目前，赵一鸣已要求全国门店整改，确保现金找零充足。"
      ],
      "imageList": ["static/zym.jpg"],
      "recommendNews": [
        {
          "id": 9,
          "title": "超市“糖果找零”屡遭吐槽，合规吗？",
          "author": "法治日报",
          "timedata": "2025.10.29"
        },
        {
          "id": 10,
          "title": "赵一鸣零食店回应“糖果找零”：全面整改",
          "author": "新京报",
          "timedata": "2025.10.29"
        }
      ],
      "comments": [
        {
          "id": 103,
          "username": "消费者小李",
          "city": "湖南长沙",
          "timedata": "1小时前",
          "content": "我也遇到过，不想要糖果还被店员说“麻烦”，太不合理了！",
          "likeCount": 345,
          "replyCount": 27,
          "liked": false
        },
        {
          "id": 104,
          "username": "商家从业者",
          "city": "浙江杭州",
          "timedata": "2小时前",
          "content": "其实硬币确实不好兑换，商家也有难处，但应该提前告知消费者",
          "likeCount": 89,
          "replyCount": 12,
          "liked": false
        }
      ]
    },
    "3": {
      "title": "698亿“国补”落地 促消费再添新动力",
      "author": "央视新闻",
      "timedata": "2025.10.02 10:30",
      "readCount": 5678,
      "shareCount": 234,
      "likeCount": 456,
      "content": [
        "近日，国家发展改革委宣布，总额698亿元的消费补贴资金正式落地，旨在进一步激发消费潜力，促进经济高质量发展。",
        "本次补贴涵盖家电、汽车、餐饮等多个消费领域，消费者在指定商家消费可享受不同比例的补贴优惠。补贴政策将持续至2025年12月31日。",
        "专家表示，此次大规模消费补贴将有效拉动内需，预计可带动社会消费品零售总额增长约2个百分点，为经济复苏注入强劲动力。"
      ],
      "imageList": ["static/guobu.png"],
      "recommendNews": [
        {
          "id": 11,
          "title": "消费补贴如何申请？最全指南来了",
          "author": "财经网",
          "timedata": "2025.10.03"
        }
      ],
      "comments": [
        {
          "id": 105,
          "username": "经济观察员",
          "city": "北京",
          "timedata": "5小时前",
          "content": "这次补贴力度很大，对刺激消费会有明显效果",
          "likeCount": 67,
          "replyCount": 8,
          "liked": false
        }
      ]
    },
    "4": {
      "title": "学习二十届四中全会精神 推进高质量发展",
      "author": "人民日报",
      "timedata": "2025.10.25 09:00",
      "readCount": 34567,
      "shareCount": 567,
      "likeCount": 1234,
      "content": [
        "党的二十大四中全会胜利召开，会议通过了一系列重要决议，为全面建设社会主义现代化国家指明了方向。",
        "会议强调，要坚持以高质量发展为主题，深化改革开放，加快构建新发展格局。各地区各部门要认真学习贯彻全会精神，把决策部署转化为推动发展的实际行动。",
        "全会提出，到2035年基本实现社会主义现代化，到本世纪中叶把我国建成富强民主文明和谐美丽的社会主义现代化强国。"
      ],
      "imageList": ["static/xuehui.jpg"],
      "recommendNews": [],
      "comments": [
        {
          "id": 106,
          "username": "党员干部",
          "city": "陕西延安",
          "timedata": "3小时前",
          "content": "要认真学习领会全会精神，落实到实际工作中",
          "likeCount": 234,
          "replyCount": 45,
          "liked": false
        }
      ]
    },
    "5": {
      "title": "亚太合作新时代：共话区域经济发展新机遇",
      "author": "新华日报",
      "timedata": "2025.10.02 14:20",
      "readCount": 28901,
      "shareCount": 345,
      "likeCount": 789,
      "content": [
        "亚太经合组织峰会近日举行，各国领导人围绕区域经济一体化、数字经济发展等议题展开深入讨论。",
        "中国代表在会议上提出多项合作倡议，强调要坚持开放包容，共建亚太命运共同体。会议通过了《亚太数字经济合作框架》，推动区域数字经济发展。",
        "与会各方一致认为，亚太地区将继续成为全球经济增长的重要引擎，要加强政策协调，深化务实合作。"
      ],
      "imageList": [],
      "recommendNews": [],
      "comments": [
        {
          "id": 107,
          "username": "国际观察",
          "city": "上海",
          "timedata": "6小时前",
          "content": "亚太地区合作前景广阔，中国发挥重要作用",
          "likeCount": 123,
          "replyCount": 23,
          "liked": false
        }
      ]
    },
    "6": {
      "title": "桂林漓江生态保护再升级，游船实行“环保动力”改造",
      "author": "桂林日报",
      "timedata": "2025.10.30 08:45",
      "readCount": 9876,
      "shareCount": 67,
      "likeCount": 234,
      "content": [
        "为加强漓江生态环境保护，桂林市启动新一轮游船环保改造计划，所有营运游船将逐步更换为电动或混合动力。",
        "此次改造预计投入资金5000万元，涉及漓江流域200余艘游船，改造后游船噪音和污染物排放将大幅降低。",
        "环保部门表示，此举将有效保护漓江水域生态环境，提升游客体验品质，预计2026年底前完成全部改造工作。"
      ],
      "imageList": ["static/lijiang.png"],
      "recommendNews": [],
      "comments": [
        {
          "id": 108,
          "username": "桂林市民",
          "city": "广西桂林",
          "timedata": "2小时前",
          "content": "支持环保改造，保护好我们的母亲河漓江",
          "likeCount": 89,
          "replyCount": 12,
          "liked": false
        }
      ]
    }
  }
};

export default {
  globalData: {
    userInfo: null,
    userData: { // 统一内存缓存，兼容视频+新闻
      likes: [], // 混合存储：新闻ID（数字）/视频ID（数字）
      collections: [], // 仅新闻
      follows: [], // 混合存储：新闻作者/视频作者
      readHistory: [], // 混合存储：新闻/视频浏览记录
      comments: {} // 仅新闻评论 {newsId: [{id, username, timedata, content, likeCount, liked}]}
    },
    userSettings: {
      avatar: '',
      nickname: '',
      syncEnabled: true
    },
    tabBarText: "未登录",
    videoData: null, // 缓存视频数据
    newsData: null  // 缓存新闻数据
  },
  
  onLaunch() {
    console.log('App 启动');
    // 隐藏 uni-icons 警告
    const originalWarn = console.warn;
    console.warn = function (...args) {
      if (args[0] && args[0].includes('Failed to resolve component: uni-icons')) {
        return;
      }
      originalWarn.apply(console, args);
    };

    this.loadUserBehaviorData();
    this.loadVideoData(); // 加载视频基础数据
    this.loadNewsData();  // 加载新闻基础数据
    setTimeout(() => {
      this.initTabBarText();
    }, 500);
  },
  
  onShow() {
    console.log('App 显示');
    setTimeout(() => {
      this.checkLoginStatus();
    }, 300);
  },
  
  onHide() {
    console.log('App 隐藏');
  },

  methods: {
    // 检查是否为TabBar页面
    isTabBarPage() {
      const tabBarPages = [
        "/pages/tabBar/demos/customViewPage/customViewPage",
        "/pages/tabBar/mine/mine"
      ];
      const pages = getCurrentPages();
      if (pages.length === 0) return false;
      const currentPage = pages[pages.length - 1].route;
      const fullPath = `/pages/${currentPage.replace(/\//g, '/')}`;
      return tabBarPages.some(page => fullPath.includes(page));
    },
    
    // 检查登录状态
    checkLoginStatus() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        this.globalData.userInfo = userInfo || null;
        this.initTabBarText();
      } catch (e) {
        console.error('检查登录状态失败:', e);
      }
    },
    
    // 初始化TabBar文本
    initTabBarText() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
          this.updateTabBarText("我的");
        } else {
          this.updateTabBarText("未登录");
        }
      } catch (e) {
        console.error('初始化TabBar失败:', e);
        this.updateTabBarText("未登录");
      }
    },
    
    // 更新TabBar文本
    updateTabBarText(text) {
      if (!this.isTabBarPage()) {
        console.log('当前非TabBar页面，跳过TabBar更新');
        this.globalData.tabBarText = text;
        return;
      }
      
      try {
        if (!text) text = "未登录";
        const displayText = text.length > 4 ? text.substring(0, 4) + "..." : text;
        const tabBarIndex = 3; 

        const updateTabBar = () => {
          uni.setTabBarItem({
            index: tabBarIndex,
            text: displayText,
            success: () => {
              console.log('TabBar更新成功:', displayText);
              this.globalData.tabBarText = displayText;
            },
            fail: (err) => {
              console.warn('TabBar更新失败，重试中:', err);
              setTimeout(() => {
                uni.setTabBarItem({
                  index: tabBarIndex,
                  text: displayText,
                  success: () => {
                    console.log('TabBar重试更新成功:', displayText);
                    this.globalData.tabBarText = displayText;
                  },
                  fail: (err2) => {
                    console.error('TabBar最终更新失败:', err2);
                  }
                });
              }, 500);
            }
          });
        };

        updateTabBar();
        
      } catch (error) {
        console.error('更新TabBar失败:', error);
        this.globalData.tabBarText = text;
      }
    },

    // 加载用户行为数据（核心：统一读取userData）
    loadUserBehaviorData() {
      try {
        // 读取统一的userData，兜底完整结构
        const userData = uni.getStorageSync('userData') || {
          likes: [],
          collections: [],
          follows: [],
          readHistory: [],
          comments: {}
        };
        // 强制数组/对象初始化，避免类型错误
        this.globalData.userData = {
          likes: Array.isArray(userData.likes) ? userData.likes : [],
          collections: Array.isArray(userData.collections) ? userData.collections : [],
          follows: Array.isArray(userData.follows) ? userData.follows : [],
          readHistory: Array.isArray(userData.readHistory) ? userData.readHistory : [],
          comments: typeof userData.comments === 'object' && userData.comments !== null ? userData.comments : {}
        };
        // 兼容原有globalData字段（避免我的页面报错）
        this.globalData.likedNews = this.globalData.userData.likes;
        this.globalData.collectedNews = this.globalData.userData.collections;
        this.globalData.followedAuthors = this.globalData.userData.follows;
        this.globalData.viewedNews = this.globalData.userData.readHistory;
        
        // 读取用户设置
        const userSettings = uni.getStorageSync('userSettings') || {
          avatar: '',
          nickname: '',
          syncEnabled: true
        };
        this.globalData.userSettings = userSettings;
        
        console.log('用户行为数据加载完成:', this.globalData.userData);
      } catch (e) {
        console.error('加载用户数据失败:', e);
        // 异常时强制重置
        this.globalData.userData = {
          likes: [],
          collections: [],
          follows: [],
          readHistory: [],
          comments: {}
        };
        this.globalData.likedNews = [];
        this.globalData.collectedNews = [];
        this.globalData.followedAuthors = [];
        this.globalData.viewedNews = [];
      }
    },

    // 加载视频基础数据（移除require，改用内联默认数据）
    loadVideoData() {
      try {
        // 方式1：优先从本地缓存读取
        const cachedVideoData = uni.getStorageSync('cloudVideoData');
        if (cachedVideoData) {
          this.globalData.videoData = cachedVideoData;
          console.log('从缓存加载视频数据成功');
        } 
        // 方式2：缓存无数据时，使用内联的默认数据
        else {
          this.globalData.videoData = DEFAULT_VIDEO_DATA;
          // 写入缓存，下次优先读取
          uni.setStorageSync('cloudVideoData', DEFAULT_VIDEO_DATA);
          console.log('使用默认视频数据并写入缓存');
        }
      } catch (e) {
        console.error('加载视频数据失败:', e);
        // 异常兜底：强制使用内联默认数据
        this.globalData.videoData = DEFAULT_VIDEO_DATA;
        uni.setStorageSync('cloudVideoData', DEFAULT_VIDEO_DATA);
      }
    },

    // 加载新闻基础数据（适配news.json结构）
    loadNewsData() {
      try {
        // 清除旧的缓存数据（避免缓存里的旧ID干扰）
        uni.removeStorageSync('cloudNewsData');
        
        // 方式1：优先从本地缓存读取（清除后会走默认数据）
        const cachedNewsData = uni.getStorageSync('cloudNewsData');
        if (cachedNewsData) {
          this.globalData.newsData = cachedNewsData;
          console.log('从缓存加载新闻数据成功:', this.globalData.newsData);
        } 
        // 方式2：缓存无数据时，使用适配后的默认数据（对应data/news.json）
        else {
          this.globalData.newsData = DEFAULT_NEWS_DATA;
          // 写入缓存，下次优先读取
          uni.setStorageSync('cloudNewsData', DEFAULT_NEWS_DATA);
          console.log('使用news.json默认数据并写入缓存:', this.globalData.newsData);
        }
      } catch (e) {
        console.error('加载新闻数据失败:', e);
        // 异常兜底：强制使用适配后的默认数据
        this.globalData.newsData = DEFAULT_NEWS_DATA;
        uni.setStorageSync('cloudNewsData', DEFAULT_NEWS_DATA);
      }
    },

    // 保存userData到本地存储
    saveUserData() {
      try {
        uni.setStorageSync('userData', this.globalData.userData);
        // 兼容原有单独存储的字段
        uni.setStorageSync('likedNews', this.globalData.userData.likes);
        uni.setStorageSync('collectedNews', this.globalData.userData.collections);
        uni.setStorageSync('followedAuthors', this.globalData.userData.follows);
        uni.setStorageSync('viewedNews', this.globalData.userData.readHistory);
      } catch (e) {
        console.error('保存userData失败:', e);
        uni.showToast({ title: '数据保存失败', icon: 'none' });
      }
    },

    // 用户登录
    userLogin(userInfo) {
      return new Promise((resolve, reject) => {
        try {
          this.globalData.userInfo = userInfo;
          uni.setStorageSync('userInfo', userInfo);
          this.updateTabBarText("我的");
          
          if (this.globalData.userSettings.syncEnabled) {
            this.syncUserData();
          }
          
          uni.$emit('userLogin', userInfo);
          resolve(true);
        } catch (e) {
          console.error('登录失败:', e);
          reject(e);
        }
      });
    },
    
    // 用户退出
    userLogout() {
      return new Promise((resolve) => {
        try {
          if (this.globalData.userSettings.syncEnabled) {
            this.backupUserData();
          }
          
          // 清空所有数据
          this.globalData.userInfo = null;
          this.globalData.userData = {
            likes: [],
            collections: [],
            follows: [],
            readHistory: [],
            comments: {}
          };
          this.globalData.likedNews = [];
          this.globalData.collectedNews = [];
          this.globalData.followedAuthors = [];
          this.globalData.viewedNews = [];
          
          // 清除本地存储
          uni.removeStorageSync('userInfo');
          uni.removeStorageSync('userData');
          uni.removeStorageSync('likedNews');
          uni.removeStorageSync('collectedNews');
          uni.removeStorageSync('followedAuthors');
          uni.removeStorageSync('viewedNews');
          
          this.updateTabBarText("未登录");
          uni.$emit('userLogout');
          uni.$emit('userDataUpdated'); // 通知我的页面刷新
          resolve(true);
        } catch (e) {
          console.error('退出登录失败:', e);
          resolve(false);
        }
      });
    },
    
    // 同步用户数据到云端（示例）
    async syncUserData() {
      if (!this.globalData.userInfo) return;
      
      try {
        const syncData = {
          userId: this.globalData.userInfo.id,
          userData: this.globalData.userData,
          syncTime: new Date().getTime()
        };
        console.log('同步用户数据:', syncData);
        uni.showToast({ title: '数据同步成功', icon: 'success' });
      } catch (e) {
        console.error('数据同步失败:', e);
        uni.showToast({ title: '数据同步失败', icon: 'none' });
      }
    },
    
    // 备份数据到本地
    backupUserData() {
      if (!this.globalData.userInfo) return;
      
      try {
        const backupData = {
          userData: this.globalData.userData,
          backupTime: new Date().getTime()
        };
        uni.setStorageSync(`cloudData_${this.globalData.userInfo.id}`, backupData);
        console.log('用户数据备份成功');
      } catch (e) {
        console.error('数据备份失败:', e);
      }
    },
    
    // 更新用户设置
    updateUserSettings(settings) {
      Object.assign(this.globalData.userSettings, settings);
      uni.setStorageSync('userSettings', this.globalData.userSettings);
    },
    
    // 更新头像
    updateUserAvatar(avatarUrl) {
      if (this.globalData.userInfo) {
        this.globalData.userInfo.avatar = avatarUrl;
        this.globalData.userSettings.avatar = avatarUrl;
        uni.setStorageSync('userInfo', this.globalData.userInfo);
        uni.$emit('userDataUpdated'); // 通知我的页面刷新头像
      }
    },
    
    // ========== 核心：点赞/收藏/关注/评论/浏览历史操作 ==========
    // 点赞新闻/视频（统一逻辑）
    likeContent(contentId, type = 'news') {
      if (!contentId || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      // 组合ID：避免新闻/视频ID冲突（可选）
      const uniqueId = type === 'video' ? `video_${contentId}` : contentId;
      if (!userData.likes.includes(uniqueId)) {
        userData.likes.push(uniqueId);
        this.saveUserData();
        uni.$emit('userDataUpdated');
        return true;
      }
      return false;
    },
    
    // 取消点赞新闻/视频
    cancelLikeContent(contentId, type = 'news') {
      if (!contentId || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      const uniqueId = type === 'video' ? `video_${contentId}` : contentId;
      userData.likes = userData.likes.filter(id => id !== uniqueId);
      this.saveUserData();
      uni.$emit('userDataUpdated');
      return true;
    },

    // 切换视频点赞（供视频组件调用）
    toggleVideoLike(videoId, isLiked) {
      if (isLiked) {
        this.likeContent(videoId, 'video');
      } else {
        this.cancelLikeContent(videoId, 'video');
      }
    },

    // 切换视频作者关注（复用新闻关注逻辑）
    toggleVideoAuthorFollow(authorName, isFollowed) {
      if (isFollowed) {
        this.followAuthor(authorName);
      } else {
        this.cancelFollow(authorName);
      }
    },
    
    // 点赞新闻（兼容原有逻辑）
    likeNews(newsId) {
      return this.likeContent(newsId, 'news');
    },
    
    // 取消点赞（兼容原有逻辑）
    cancelLike(newsId) {
      return this.cancelLikeContent(newsId, 'news');
    },
    
    // 收藏新闻
    collectNews(newsId) {
      if (!newsId || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      if (!userData.collections.includes(newsId)) {
        userData.collections.push(newsId);
        this.saveUserData();
        uni.$emit('userDataUpdated');
        return true;
      }
      return false;
    },
    
    // 取消收藏
    cancelCollect(newsId) {
      if (!newsId || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      userData.collections = userData.collections.filter(id => id !== newsId);
      this.saveUserData();
      uni.$emit('userDataUpdated');
      return true;
    },
    
    // 关注作者（新闻/视频通用）
    followAuthor(authorName) {
      if (!authorName || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      if (!userData.follows.includes(authorName)) {
        userData.follows.push(authorName);
        this.saveUserData();
        uni.$emit('userDataUpdated');
        return true;
      }
      return false;
    },
    
    // 取消关注（新闻/视频通用）
    cancelFollow(authorName) {
      if (!authorName || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      userData.follows = userData.follows.filter(name => name !== authorName);
      this.saveUserData();
      uni.$emit('userDataUpdated');
      return true;
    },
    
    // 记录浏览历史（新闻/视频通用，适配news.json字段）
    recordView(contentId, contentInfo, type = 'news') {
      if (!contentId || !contentInfo || !this.globalData.userInfo) return;
      const userData = this.globalData.userData;
      // 组合ID避免冲突
      const uniqueId = type === 'video' ? `video_${contentId}` : contentId;
      // 去重
      userData.readHistory = userData.readHistory.filter(item => item.id !== uniqueId);
      // 添加新记录（适配news.json的字段）
      userData.readHistory.unshift({
        id: uniqueId,
        type: type, // 标记类型：news/video
        title: contentInfo.title || '',
        author: contentInfo.author || '',
        image: contentInfo.cover || (contentInfo.imageList && contentInfo.imageList[0]) || '',
        readTime: new Date().getTime(),
        timedata: contentInfo.timedata || '' // 新增适配news.json的时间字段
      });
      // 限制数量
      if (userData.readHistory.length > 100) {
        userData.readHistory = userData.readHistory.slice(0, 100);
      }
      this.saveUserData();
      uni.$emit('userDataUpdated');
    },
    
    // 添加评论（仅新闻，适配news.json评论结构）
    addComment(newsId, comment) {
      if (!newsId || !comment || !this.globalData.userInfo) return [];
      const userData = this.globalData.userData;
      
      // 初始化该新闻的评论数组
      if (!userData.comments[newsId]) {
        userData.comments[newsId] = [];
      }
      
      // 补全news.json的评论字段（city/replyCount等）
      const completeComment = {
        id: comment.id || Date.now(),
        username: comment.username || this.globalData.userInfo.nickname || '匿名用户',
        city: comment.city || '',
        timedata: comment.timedata || '刚刚',
        content: comment.content || '',
        likeCount: comment.likeCount || 0,
        replyCount: comment.replyCount || 0,
        liked: comment.liked || false
      };
      
      // 去重添加评论
      const isExist = userData.comments[newsId].some(item => item.id === completeComment.id);
      if (!isExist) {
        userData.comments[newsId].unshift(completeComment);
        this.saveUserData();
        uni.$emit('userDataUpdated');
      }
      
      return userData.comments[newsId];
    },
    
    // 获取新闻评论
    getComments(newsId) {
      if (!newsId) return [];
      const userData = this.globalData.userData;
      // 优先返回news.json自带的评论，再合并用户新增的评论
      const defaultComments = this.globalData.newsData?.newsDetails?.[newsId]?.comments || [];
      const userComments = userData.comments[newsId] || [];
      // 合并并去重（以ID为准）
      const mergedComments = [...defaultComments, ...userComments].reduce((acc, curr) => {
        if (!acc.some(item => item.id === curr.id)) {
          acc.push(curr);
        }
        return acc;
      }, []);
      return mergedComments;
    },
    
    // 点赞评论（适配news.json评论结构）
    likeComment(newsId, commentId) {
      if (!newsId || !commentId || !this.globalData.userInfo) return;
      const userData = this.globalData.userData;
      
      // 先更新用户自定义评论
      if (userData.comments[newsId]) {
        const commentIndex = userData.comments[newsId].findIndex(item => item.id === commentId);
        if (commentIndex > -1) {
          userData.comments[newsId][commentIndex].liked = !userData.comments[newsId][commentIndex].liked;
          if (userData.comments[newsId][commentIndex].liked) {
            userData.comments[newsId][commentIndex].likeCount = (userData.comments[newsId][commentIndex].likeCount || 0) + 1;
          } else {
            userData.comments[newsId][commentIndex].likeCount = Math.max(0, (userData.comments[newsId][commentIndex].likeCount || 0) - 1);
          }
          this.saveUserData();
          uni.$emit('userDataUpdated');
          return;
        }
      }
      
      // 再更新news.json自带的评论（临时修改内存数据）
      if (this.globalData.newsData?.newsDetails?.[newsId]?.comments) {
        const defaultCommentIndex = this.globalData.newsData.newsDetails[newsId].comments.findIndex(item => item.id === commentId);
        if (defaultCommentIndex > -1) {
          this.globalData.newsData.newsDetails[newsId].comments[defaultCommentIndex].liked = !this.globalData.newsData.newsDetails[newsId].comments[defaultCommentIndex].liked;
          if (this.globalData.newsData.newsDetails[newsId].comments[defaultCommentIndex].liked) {
            this.globalData.newsData.newsDetails[newsId].comments[defaultCommentIndex].likeCount += 1;
          } else {
            this.globalData.newsData.newsDetails[newsId].comments[defaultCommentIndex].likeCount = Math.max(0, this.globalData.newsData.newsDetails[newsId].comments[defaultCommentIndex].likeCount - 1);
          }
          uni.$emit('userDataUpdated');
        }
      }
    },
    
    // 分享新闻
    shareNews(newsId) {
      if (!newsId) return;
      // 模拟分享逻辑
      uni.showActionSheet({
        itemList: ['分享到微信', '分享到朋友圈', '分享到QQ'],
        success: (res) => {
          console.log('分享成功:', res.tapIndex);
          uni.showToast({ title: '分享成功', icon: 'success' });
        },
        fail: (err) => {
          console.log('分享取消:', err);
        }
      });
    },
    
    // 检查是否点赞
    isLiked(contentId, type = 'news') {
      if (!contentId || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      const uniqueId = type === 'video' ? `video_${contentId}` : contentId;
      return userData.likes.includes(uniqueId);
    },
    
    // 检查是否收藏
    isCollected(newsId) {
      if (!newsId || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      return userData.collections.includes(newsId);
    },
    
    // 检查是否关注作者
    isFollowed(authorName) {
      if (!authorName || !this.globalData.userInfo) return false;
      const userData = this.globalData.userData;
      return userData.follows.includes(authorName);
    }
  }
};
</script>

<style>
/* 全局样式重置 */
page {
  background-color: #f8f9fa;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, sans-serif;
}

/* 全局滚动条样式 */
::-webkit-scrollbar {
  width: 4rpx;
  height: 4rpx;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2rpx;
}

::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 2rpx;
}

::-webkit-scrollbar-thumb:hover {
  background: #999;
}
</style>